package com.ruoyi.shop.service.impl;

import java.util.HashMap;
import java.util.List;

import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.shop.domain.ShopProductCategory;
import com.ruoyi.shop.domain.vo.ShopProductSimpleVo;
import com.ruoyi.shop.domain.vo.ShopProductVo;
import com.ruoyi.shop.service.IShopProductCategoryService;
import com.ruoyi.shop.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.shop.mapper.ShopProductMapper;
import com.ruoyi.shop.domain.ShopProduct;
import com.ruoyi.shop.service.IShopProductService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品Service业务层处理
 * 
 * @author Alan Zhang
 * @date 2021-09-14
 */
@Service
public class ShopProductServiceImpl implements IShopProductService 
{
    @Autowired
    private ShopProductMapper shopProductMapper;
    @Autowired
    private IShopProductCategoryService shopProductCategoryService;
    /**
     * 查询商品
     * 
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public ShopProduct selectShopProductById(Long id)
    {
        return shopProductMapper.selectShopProductById(id);
    }

    /**
     * 查询商品
     * 部分信息
     * @param id 商品主键
     * @return 商品
     */
    public ShopProductSimpleVo selectShopProductSimpleVoById(Long id){
        return shopProductMapper.selectShopProductSimpleVoById(id);
    }

    /**
     * 查询商品列表
     * 
     * @param shopProduct 商品
     * @return 商品
     */
    @Override
    public List<ShopProduct> selectShopProductList(ShopProduct shopProduct)
    {
        return shopProductMapper.selectShopProductList(shopProduct);
    }

    /**
     * 新增商品
     * 
     * @param shopProduct 商品
     * @return 结果
     */
    @Override
    public int insertShopProduct(ShopProduct shopProduct)
    {
        shopProduct.setCreateTime(DateUtils.getNowDate());
        return shopProductMapper.insertShopProduct(shopProduct);
    }

    /**
     * 修改商品
     * 
     * @param shopProduct 商品
     * @return 结果
     */
    @Override
    public int updateShopProduct(ShopProduct shopProduct)
    {
        shopProduct.setUpdateTime(DateUtils.getNowDate());
        return shopProductMapper.updateShopProduct(shopProduct);
    }

    /**
     * 批量删除商品
     * 
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteShopProductByIds(String ids)
    {
        return shopProductMapper.deleteShopProductByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除商品信息
     * 
     * @param id 商品主键
     * @return 结果
     */
    @Override
    public int deleteShopProductById(Long id)
    {
        return shopProductMapper.deleteShopProductById(id);
    }


    /**
     * 商品编号 查询商品信息
     * @param productNo
     * @return
     */
    @Override
    public ShopProductVo selectShopProductByProductNo(String productNo){
        if(StringUtils.isEmpty(productNo)){
            return null;
        }
        return shopProductMapper.selectShopProductByProductNo(productNo);
    }

    /**
     * 根据名称 商品Id
     * @param title
     * @return
     */
    @Override
    public Long selectShopProductByProductName(String title){
        return shopProductMapper.selectShopProductByProductName(title);
    }


    /**
     *小程序 查询商品
     *
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public ShopProductSimpleVo selectShopProductBoById(Long id){
        return shopProductMapper.selectShopProductBoById(id);
    }

    /**
     * 小程序 新品产品
     * @return
     */
    @Override
    public List<ShopProductSimpleVo> selectNewShopProduct(){
        return shopProductMapper.selectNewShopProduct();
    }

    /**
     * 小程序 热卖产品
     * @param realSalesCount
     * @return
     */
    @Override
    public List<ShopProductSimpleVo> selectHotShopProduct(Integer realSalesCount){
        return shopProductMapper.selectHotShopProduct(realSalesCount);
    }

    /**
     * 小程序 特价产品
     * @return
     */
    @Override
    public List<ShopProductSimpleVo> selectIsSpecialShopProduct(){
        return shopProductMapper.selectIsSpecialShopProduct();
    }

    /**
     * 小程序 普通产品
     * @return
     */
    @Override
    public List<ShopProductSimpleVo> selectShopProductAll(){
        return shopProductMapper.selectShopProductAll();
    }

    /**
     * 分类下的商品
     * @param categoryId
     * @return
     */
    @Override
    public List<ShopProductSimpleVo> selectJoinShopProductByCategoryId(Long categoryId){
        return shopProductMapper.selectJoinShopProductByCategoryId(categoryId);
    }

    /**
     * 根据商品名称搜索
     * @param title
     * @return
     */
    @Override
    public List<ShopProductSimpleVo> selectShopProductByTitle(String title){
        return shopProductMapper.selectShopProductByTitle(title);
    }

    /**
     * 导入商品信息
     * @param dataList
     * @param optName
     * @return
     */
    @Transactional
    @Override
    public String importProductInfo(List<ProductVo> dataList, Long supplierId, String optName) {
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new BusinessException("未发现可导入的信息！");
        }
        if(supplierId == null){
            throw new BusinessException("请选择供应商！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        HashMap<String,Long> categoryMap = new HashMap<>();
        long i = 1;
        for (ProductVo entity : dataList)
        {
            i++;
            if(StringUtils.isEmpty(entity.getName()) || StringUtils.isEmpty(entity.getProductNo())){
                failureNum++;
                failureMsg.append("<br/>" + i + "、请填写商品名称");
                continue;
            }
            if(StringUtils.isEmpty(entity.getProductNo())){
                failureNum++;
                failureMsg.append("<br/>" + i + "、请填写商品编码");
                continue;
            }
            if(entity.getPrice() == null){
                failureNum++;
                failureMsg.append("<br/>" + i + "、[" + entity.getName() + "] 请填写价格");
                continue;
            }

            if(StringUtils.isNotEmpty(entity.getCategoryName())) {
                if(!categoryMap.containsKey(entity.getCategoryName())){

                    Long id = shopProductCategoryService.selectShopProductCategoryByName(entity.getCategoryName());
                    if(id == null){
                        ShopProductCategory shopProductCategory = new ShopProductCategory();
                        shopProductCategory.setTitle(entity.getCategoryName());
                        shopProductCategory.setOrderNumber(1L);
                        shopProductCategory.setType("1");
                        int rows = shopProductCategoryService.insertShopProductCategory(shopProductCategory);
                        if(rows > 0){
                            categoryMap.put(entity.getCategoryName(), shopProductCategory.getId());
                        }
                    } else {
                        categoryMap.put(entity.getCategoryName(), id);
                    }
                }
            }

            ShopProductVo shopProductVo = selectShopProductByProductNo(entity.getProductNo());
            if(shopProductVo == null){
                ShopProduct shopProduct = new ShopProduct();
                shopProduct.setTitle(entity.getName());
                shopProduct.setProductNo(entity.getProductNo());
                shopProduct.setPrice(entity.getPrice());

                if(StringUtils.isNotEmpty(entity.getCategoryName())){
                    Long categoryId = categoryMap.get(entity.getCategoryName());
                    shopProduct.setCategoryId(categoryId);
                }
                shopProduct.setStatus(1); //默认上架
                shopProduct.setIsSpecial(0); //不是特价
                shopProduct.setSupplierId(supplierId);
                shopProduct.setOrderNumber(i);
                int res = insertShopProduct(shopProduct);
                if(res > 0) {
                    successNum++;
                    successMsg.append("<br/>" + i + "、 [" + entity.getName() + "] 成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + i + "、[" + entity.getName() + "] 失败");
                }
            } else {

                if(shopProductVo.getPrice().compareTo(entity.getPrice()) != 0){
                    ShopProduct shopProduct = new ShopProduct();
                    shopProduct.setId(shopProductVo.getId());//数据存在的商品
                    shopProduct.setPrice(entity.getPrice()); //变更价格
                    int rows = updateShopProduct(shopProduct);
                    if(rows > 0) {
                        successNum++;
                        successMsg.append("<br/>" + i + "、 [" + entity.getName() + "] 成功");
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>" + i + "、[" + entity.getName() + "] 失败");
                    }
                } else {
                    System.out.println("*****价格未变化，无需处理*****");
                }
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    /**
     * 导入商品价格同步信息
     * @param dataList
     * @param optName
     * @return
     */
    @Transactional
    @Override
    public String importProductPrice(List<ProductVo> dataList, Long supplierId, String optName) {
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new BusinessException("未发现可导入的信息！");
        }
        if(supplierId == null){
            throw new BusinessException("请选择供应商！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        int i = 1;
        for (ProductVo entity : dataList)
        {
            i++;
            if(StringUtils.isEmpty(entity.getName()) || StringUtils.isEmpty(entity.getProductNo())){
                failureNum++;
                failureMsg.append("<br/>" + i + "、请填写商品名称");
                continue;
            }
            if(StringUtils.isEmpty(entity.getProductNo())){
                failureNum++;
                failureMsg.append("<br/>" + i + "、请填写商品编码");
                continue;
            }
            if(entity.getPrice() == null){
                failureNum++;
                failureMsg.append("<br/>" + i + "、[" + entity.getName() + "] 请填写价格");
                continue;
            }

            ShopProductVo shopProductVo = selectShopProductByProductNo(entity.getProductNo());
            if(shopProductVo != null){

                if(shopProductVo.getPrice().compareTo(entity.getPrice()) != 0){
                    ShopProduct shopProduct = new ShopProduct();
                    shopProduct.setId(shopProductVo.getId());//数据存在的商品
                    shopProduct.setPrice(entity.getPrice()); //变更价格
                    int rows = updateShopProduct(shopProduct);
                    if(rows > 0) {
                        successNum++;
                        successMsg.append("<br/>" + i + "、 [" + entity.getName() + "] 成功");
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>" + i + "、[" + entity.getName() + "] 失败");
                    }
                } else {
                    System.out.println("*****价格未变化，无需处理*****");
                }
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部同步成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
